using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace MCromwell.StaffIntranet.Core
{
    public class Email : IHasValidation
    {
        // taken from regexlib conforms to RFC 2822
        private const string regexValidationPattern = @"^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|""((?=[\x01-\x7f])[^""\\]|\\[\x01-\x7f])*""\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|""((?=[\x01-\x7f])[^""\\]|\\[\x01-\x7f])*"")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$";
        private Regex emailRegex;
        private string innerValue;

        public Email(string address)
        {
            innerValue = address;
        }
               
        public string Value
        {
            get
            {
                return innerValue;
            }
        }

        public void Set(string newAddress)
        {
            innerValue = newAddress;
        }

        public static implicit operator string(Email rhs)
        {
            return rhs.Value;
        }


        public DomainObjectValidationResult Validate()
        {
            DomainObjectValidationResult result = new DomainObjectValidationResult();
            emailRegex = new Regex(regexValidationPattern, RegexOptions.Compiled);
            if (!emailRegex.IsMatch(innerValue))
                result.Register(new ValidationResultItem("emailaddress", "Email address is invalid"));
            
            return result;
        }
    }
}
